package com.renshine.base.util;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.jolbox.bonecp.BoneCPDataSource;
import com.renshine.base.bean.Field;
import com.renshine.base.bean.Table;
import com.renshine.base.dao.QueryDao;

/**
 * 
 * bean的手动管理工具
 * 
 * @author deyang
 *
 */
@Component
public class ContextBeanUtil implements ApplicationContextAware{

	private static Logger log = LoggerFactory.getLogger(ContextBeanUtil.class);
	private static ApplicationContext CONTEXT;
	
	/**
	 * 将数据源注入到容器中QueryDao的实现类对象中
	 * 
	 * @param dataSource 数据源
	 * @param dialect 方言
	 */
	@SuppressWarnings("unchecked")
	public static void fill(BoneCPDataSource dataSource, String dialect) {
		QueryDao dao = CONTEXT.getBean(QueryDao.class);
		dao.setDataSource(dataSource);
		
		Object obj1 = CONTEXT.getBean(dialect + "TableMapper");
		if (obj1 == null) {
			throw new RuntimeException("没有配置" + dialect + "对就应的TableMapper实现类");
		}
		dao.setTableRowMapper((RowMapper<Table>)obj1);
		
		Object obj2 = CONTEXT.getBean(dialect + "FieldMapper");
		if (obj2 == null) {
			throw new RuntimeException("没有配置" + dialect + "对就应的FieldMapper实现类");
		}
		dao.setFieldRowMapper((RowMapper<Field>)obj2);
	}
	
	/**
	 * 读取配置文件
	 * 
	 * @param location 文件路径
	 * @return 对应的资源
	 */
	public static Resource getResource (String location) {
		return CONTEXT.getResource(location);
	}
	
	/**
	 * 读取配置文件
	 * 
	 * @param locationPattern
	 * @return 对应的资源集合
	 */
	public static Resource[] getResources (String locationPattern) {
		try {
			return CONTEXT.getResources(locationPattern);
		} catch (IOException e) {
			log.error("加载{}配置出错", locationPattern);
			return null;
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		ContextBeanUtil.CONTEXT = context;
		log.info("ContextBeanUtil初始化成功!");
	}

}
